package com.zyt.demo.foundation;

import java.io.*;

public class StreamDemo {
    public static void main(String[] args) throws IOException {
        copyUseBufferedStream();
        copyUseNormalStream();
    }

    /**
     * 使用缓冲流拷贝文件
     * @throws IOException
     */
    public static void copyUseBufferedStream() throws IOException {
        long start = System.currentTimeMillis();

        File iFile = new File("Resource/Stream/1581653973686.jpg");
        File oFile = new File("Resource/Stream/1581653973686-copy.jpg");
        if (oFile.exists()) {
            oFile.createNewFile();
        }
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(iFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(oFile));
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) > 0) {
            bos.write(bytes, 0, len);
        }

        bis.close();
        bos.flush();
        bos.close();

        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("time = " + time);
    }

    /**
     * 使用普通流拷贝文件
     * @throws IOException
     */
    public static void copyUseNormalStream() throws IOException {
        long start = System.currentTimeMillis();
        File iFile = new File("Resource/Stream/1581653973686.jpg");
        File oFile = new File("Resource/Stream/1581653973686-copy-with-tream.jpg");
        if (oFile.exists()) {
            oFile.createNewFile();
        }
        FileInputStream fis = new FileInputStream(iFile);
        FileOutputStream fos = new FileOutputStream(oFile);
        int data;
        while ((data = fis.read()) != -1) {
            fos.write(data);
        }

        fis.close();
        fos.flush();
        fos.close();

        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("time = " + time);
    }
}
